//
//  NRWCarShareTagVC.m
//  New_Runway
//
//  Created by 邢毅 on 2018/6/1.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarShareTagVC.h"
#import "NRWCarTemplateShareCell.h"
#import "NRWCarChooseTagView.h"
#import "NRWCarSharePictureModel.h"
#import "NRWTemplateAlertView.h"
#import "NRWCarShareTemplateManager.h"
#import "UIImage+ImageCompress.h"

@interface NRWCarShareTagVC ()<UICollectionViewDelegate, UICollectionViewDataSource, NRWCarChooseTagViewDelegate, NRWTemplateAlertViewDelegate>

@property (strong, nonatomic) NSArray *imageArr; /**< 图片数组, 为了给图片浏览器使用 */

@end

@implementation NRWCarShareTagVC
{
    UICollectionView *_collection;
    NRWCarChooseTagView *_tagView;
    NSArray <NRWCarSharePictureModel *>*_needTagImageArr; /**< 需要生成标签的图片模型数组 */
    NSArray <UIImage *>*_tagImageArr; /**< 标签图片数组 */
    NSString *_selectedTagImageName;
    NSString *_shortUrl;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _selectedTagImageName = @"share_canbooked";
    
    [self filterCarImageArr];
    
    [self loadShortUrl];
    
    [self setupNavigation];
    
    [self setupCollection];
    
    [self setupChooseTagView];
    
    self.view.backgroundColor = MAIN_BACKGROUND_COLOR();
}

- (void)viewDidLayoutSubviews {
    
    [super viewDidLayoutSubviews];
    
    [_collection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(self.navH);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(_tagView.mas_top);
    }];
    
    [_tagView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(- 23 * screen_height_scale - getSafeBottomMargin());
        make.height.equalTo(@70);
    }];
}

- (void)filterCarImageArr {
    
    NSMutableArray *arrM = [NSMutableArray array];
    for (NRWCarSharePictureModel *model in self.imageModelArr) {
        
        if (model.imageType != SharePictureTypeCode) {
            [arrM addObject:model];
        }
    }
    _needTagImageArr = arrM.copy;
    
    [_collection reloadData];
}

- (void)setupNavigation {
    
    self.navigationBarView.titleLabel.text = @"标签分享";
    [self.navigationBarView.rightItem setTitle:@"去分享" forState:UIControlStateNormal];
}

- (void)setupCollection {
    
    int itemWH = ((int)Screen_width - 40) / 3;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(itemWH, itemWH);
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    _collection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    _collection.backgroundColor = MAIN_BACKGROUND_COLOR();
    _collection.delegate = self;
    _collection.dataSource = self;
    [_collection registerClass:NRWCarTemplateShareCell.class forCellWithReuseIdentifier:@"cell"];
    _collection.contentInset = UIEdgeInsetsMake(10, 10, -10, 10);
    [self.view addSubview:_collection];
}

- (void)setupChooseTagView {
    
    _tagView = [[NRWCarChooseTagView alloc] init];
    _tagView.delegate = self;
    [self.view addSubview:_tagView];
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return _needTagImageArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    NRWCarTemplateShareCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.image = _needTagImageArr[indexPath.item].picture;
    cell.tagImage = getImageFromName(_selectedTagImageName);
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [HUPhotoBrowser showFromImageView:nil withImages:self.imageArr atIndex:indexPath.item];
}

#pragma mark - NRWCarChooseTagViewDelegate
- (void)carChooseTagView:(NRWCarChooseTagView *)view itemBtnDidClick:(UIButton *)sender aiIndex:(NSInteger)index tagImageName:(NSString *)tagImageName {
    
    _selectedTagImageName = tagImageName;
    
    [_collection reloadData];
}

#pragma mark - NRWTemplateAlertViewDelegate
- (void)templateAlertView:(NRWTemplateAlertView *)view copyDidClick:(UIButton *)sender {
    
    [view dismiss];
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = view.contentText;
    
    [self getTagImage];
    
    
}

- (void)templateAlertView:(NRWTemplateAlertView *)view notCopyDidClick:(UIButton *)sender {
    
    [view dismiss];
    
    [self getTagImage];
}

- (void)templateAlertView:(NRWTemplateAlertView *)view closeBtnDidClick:(UIButton *)sender {
    
    [view dismiss];
}

#pragma mark - 获取添加标签后的图片
- (void)getTagImage {
    
    [SVProgressHUD show];
    dispatch_queue_t queue = dispatch_queue_create("com.nrw.image", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:_needTagImageArr.count];
        
        for (NRWCarSharePictureModel *model in _needTagImageArr) {
            
            UIImage *image = model.picture;
            
            CGFloat scale = image.size.width / 375.0;
            CGFloat tagWidth = 40 * scale;
            CGFloat tagHeight = 36 * scale;
            
            UIImage *tagImage = [NRWCarShareTemplateManager getDrawTagImageArrWithOriginalImage:model.picture tagImage:getImageFromName(_selectedTagImageName) tagImageRect:CGRectMake(image.size.width - tagWidth - 2 *scale, image.size.height - tagHeight - 5 * scale, tagWidth, tagHeight)];
            
            [arrM addObject:tagImage];
        }
        _tagImageArr = arrM.copy;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [self showShareViewController];
        });
    });
}

#pragma mark - rightItemClick
- (void)rightItemClick {
    
    NRWTemplateAlertView *alertView = [[NRWTemplateAlertView alloc] init];
    alertView.delegate = self;
    [alertView show];
    
    Result *model = _needTagImageArr.firstObject.CarModel;
    
    alertView.contentText = [NRWCarShareTemplateManager getShareTextWithCarTitle:model.carTitle carPrice:model.carRetailPrice carLicenceDate:model.carLicenceDate carLicenceState:model.carLicenceState carMileage:model.carMileage shortUrl:_shortUrl carCount:self.carCount];
}

#pragma mark - loadShortUrl
- (void)loadShortUrl {
    
    if (self.carCount == 1) {
        
        Result *model = _needTagImageArr.firstObject.CarModel;
        
        [YQNetworking postWithUrl:@"http://api.t.sina.com.cn/short_url/shorten.json" refreshRequest:NO cache:NO params:@{@"source": @"3271760578", @"url_long": [NSString getShareCarDetailUrlWithMarketId:model.marketId shopId:model.shopId carId:model.carId]} progressBlock:nil successBlock:^(id response) {
            
            if (isArrayClass(response)) {
                if (isDictionaryClass([response firstObject])) {
                    _shortUrl = [response firstObject][@"url_short"];
                }
            }
        } failBlock:^(NSError *error) {
            
            [ShowMessage showHintMessage:@"车辆链接生成失败, 请稍后再试" duration:1.5 withRemindId:remindWarning];
        }];
    }
}

#pragma mark - 展示分享弹框
- (void)showShareViewController {

    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:_tagImageArr applicationActivities:nil];
    
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (activityError) {
            [ShowMessage showHintMessage:@"分享出错, 请稍后再试" duration:1.5 withRemindId:remindWarning];
        }
    };
    
    NSMutableArray *arrM = @[UIActivityTypePostToFacebook,
                             UIActivityTypePostToTwitter,
                             UIActivityTypePostToWeibo,
                             UIActivityTypeMessage,
                             UIActivityTypeMail,
                             UIActivityTypePrint,
                             UIActivityTypeCopyToPasteboard,
                             UIActivityTypeAssignToContact,
                             UIActivityTypeSaveToCameraRoll,
                             UIActivityTypeAddToReadingList,
                             UIActivityTypePostToFlickr,
                             UIActivityTypePostToVimeo,
                             UIActivityTypePostToTencentWeibo,
                             UIActivityTypeAirDrop].mutableCopy;
    if (@available(iOS 9.0, *)) {
        [arrM addObject:UIActivityTypeOpenInIBooks];
    }
    
    if (@available(iOS 11.0, *)) {
        [arrM addObject:UIActivityTypeMarkupAsPDF];
    }
    
    activityVC.excludedActivityTypes = arrM.copy;
    [self presentViewController:activityVC animated:YES completion:nil];
}

#pragma mark - getter
- (NSArray *)imageArr {
    
    if (_imageArr == nil) {
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:_needTagImageArr.count];
        for (NRWCarSharePictureModel *model in _needTagImageArr) {
            [arrM addObject:model.picture];
        }
        _imageArr = arrM.copy;
    }
    return _imageArr;
}

@end
